<template>
  <div>
    <!-- file-list用于默认图片的回显 -->
    <el-upload
      action="#"
      list-type="picture-card"
      :http-request="uploadImg"
      :on-remove="removeImg"
      :class="{disable: imgUrl}"
      :file-list="fileList"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 进度条在没上传之前隐藏 上传中显示 -->
    <!-- percentage设置当前进度值 -->
    <el-progress v-show="percent>0&&percent<100" :percentage="percent" />
  </div>
</template>
<script>
// 实例化cos服务
import COS from 'cos-js-sdk-v5'
// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDrY6nPqGiwMYntsjQxITWQBmXCva8h4GR',
  SecretKey: 'EdtyyV10rYExfaMZgrHkGeYJVbfaN5Pv'
})
export default {
  data() {
    return {
      imgUrl: '',
      percent: 0
    }
  },
  computed: {
    fileList() {
      return this.imgUrl ? [{ url: this.imgUrl }] : []
    }
  },
  methods: {
    uploadImg(file) {
      // 自定义图片上传
      // file就是选中的文件对象，其中里面有一个file属性
      // 那么这个属性就是将来要传递给后端的文件对象
      // 调用腾讯云提供的方法 实现文件上传
      this.imgUrl = file.file // 为了让上传效果立刻消失
      cos.uploadFile(
        {
          Bucket: 'hr-82-1314826488',
          Region: 'ap-nanjing',
          Key: Date.now().toString(),
          Body: file.file,
          SliceSize: 1024 * 1024 * 5,
          onProgress: (progressData) => {
            this.percent = progressData.percent * 100
          }
        }, (err, data) => {
          if (err) {
            console.log('上传失败', err)
            this.imgUrl = ''
          } else {
            console.log('上传成功', this)
            this.imgUrl = 'http://' + data.Location
          }
        })
    },
    // 移除图片
    removeImg() {
      this.imgUrl = ''
    }
  }
}
</script>
  <style lang="scss" scoped>
  .disable{
      ::v-deep .el-upload--picture-card{
          display: none;
      }
  }
  .el-progress{
    position: absolute;
      width: 170px;
  }
  </style>

